package com.wzh.loveEmail.service.Impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.wzh.loveEmail.bean.WeatherInfo;
import com.wzh.loveEmail.config.LoveConfig;
import com.wzh.loveEmail.config.TianApiConfig;
import com.wzh.loveEmail.service.ApiService;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * 邮件业务类
 *
 * @author qzz
 */
@Service
public class MailService {
    private static final Logger logger = LoggerFactory.getLogger(MailService.class);

    @Autowired
    private ApiService apiService;

    @Autowired
    private JavaMailSenderImpl javaMailSender;

    @Value("${spring.mail.username}")
    private String sendMailer;

    @Autowired
    private TianApiConfig tianApiConfig;

    @Autowired
    private LoveConfig loveConfig;

    /**
     * 检测邮件信息类
     *
     * @param to
     * @param subject
     * @param text
     */
    private void checkMail(String to, String subject, String text) {
        if (StrUtil.isEmpty(to)) {
            throw new RuntimeException("邮件收信人不能为空");
        }
        if (StrUtil.isEmpty(subject)) {
            throw new RuntimeException("邮件主题不能为空");
        }
        if (StrUtil.isEmpty(text)) {
            throw new RuntimeException("邮件内容不能为空");
        }
    }

    /**
     * 发送纯文本邮件
     *
     * @param to
     * @param subject
     * @param text
     */
    public void sendTextMailMessage(String to, String subject, String text) {
        MimeMessageHelper mimeMessageHelper = null;
        try {
            //true 代表支持复杂的类型
            mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(to.split(","));
            //邮件主题
            mimeMessageHelper.setSubject(subject);
            //邮件内容
            mimeMessageHelper.setText(text);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());
        } catch (MessagingException e) {
            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            System.out.println("发送邮件成功：" + sendMailer + "->" + to);
        }

    }

    /**
     * 发送html邮件
     *
     * @param to
     * @param subject
     * @param content
     */
    public void sendHtmlMailMessage(String to, String subject, String content) {
        try {
            //true 代表支持复杂的类型
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(), true);
            //邮件发信人
            mimeMessageHelper.setFrom(sendMailer);
            //邮件收信人  1或多个
            mimeMessageHelper.setTo(to.split(","));
            //邮件主题
            mimeMessageHelper.setSubject(subject);
            //邮件内容   true 代表支持html
            mimeMessageHelper.setText(content, true);
            //邮件发送时间
            mimeMessageHelper.setSentDate(new Date());

            //发送邮件
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
            System.out.println("发送邮件成功：" + sendMailer + "->" + to);

        } catch (MessagingException e) {
            e.printStackTrace();
            System.out.println("发送邮件失败：" + e.getMessage());
        }
    }


    @SneakyThrows
    public String getTemplateContent() {
        Resource resource = new ClassPathResource("templates/emailTemplate.html");
        try (InputStream inputStream = resource.getInputStream()) {
            return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
        }
    }


    String testWeatherJsonString = "{\"date\":\"2024-12-10\",\"week\":\"星期二\",\"province\":\"广东\",\"area\":\"佛山\",\"areaid\":\"101280800\",\"weather\":\"多云转阴\",\"weatherimg\":\"yin.png\",\"weathercode\":\"duoyun_yin\",\"real\":\"21℃\",\"lowest\":\"18℃\",\"highest\":\"23℃\",\"wind\":\"北风\",\"windspeed\":\"3\",\"windsc\":\"1-3级\",\"sunrise\":\"06:59\",\"sunset\":\"17:44\",\"moonrise\":\"13:41\",\"moondown\":\"01:30\",\"pcpn\":\"0.0\",\"uv_index\":\"4\",\"vis\":\"25\",\"humidity\":\"63\",\"tips\":\"天气暖和，适宜着单层面料的短套装、T恤衫、薄牛仔、休闲服、职业套装等春秋过渡装。年老体弱者请适当增减衣服。\"}";

    public String getHtml() {
        String template = getTemplateContent();
//        WeatherInfo weather = JSONUtil.toBean(testWeatherJsonString, WeatherInfo.class);
        WeatherInfo weather = apiService.getWeatherInfo(tianApiConfig.getArea());
        return template
                .replace("{{DATE}}", String.valueOf(weather.getDate()))
                .replace("{{AREA}}", String.valueOf(weather.getArea()))
                .replace("{{WEEK}}", String.valueOf(weather.getWeek()))
                .replace("{{WEATHER_IMG}}", String.valueOf(weather.getWeatherimg()))
                .replace("{{WEATHER}}", String.valueOf(weather.getWeather()))
                .replace("{{LOWEST}}", String.valueOf(weather.getLowest()))
                .replace("{{HIGHEST}}", String.valueOf(weather.getHighest()))
                .replace("{{WIND}}", String.valueOf(weather.getWind()))
                .replace("{{WINDSC}}", String.valueOf(weather.getWindsc()))
                .replace("{{WINDSPEED}}", String.valueOf(weather.getWindspeed()))
                .replace("{{SUNRISE}}", String.valueOf(weather.getSunrise()))
                .replace("{{SUNSET}}", String.valueOf(weather.getSunset()))
                .replace("{{PCPN}}", String.valueOf(weather.getPcpn()))
//                .replace("{{POP}}", weather.getPop())
                .replace("{{HUMIDITY}}", String.valueOf(weather.getHumidity()))
                .replace("{{UV_INDEX}}", String.valueOf(weather.getUvIndex()))
                .replace("{{TIPS}}", String.valueOf(weather.getTips()))
                .replace("{{LOVE_DAYS}}", String.valueOf(calculateLoveDays()))
                .replace("{{MY_BIRTHDAY_COUNT}}", String.valueOf(calculateMyBirthdayCountdown()))
                .replace("{{BB_BIRTHDAY_COUNT}}", String.valueOf(calculateBbBirthdayCountdown()))
                .replace("{{CAIHONGPI}}", String.valueOf(apiService.getCaiHongPiInfo()))
                .replace("{{DOG_DIARY}}", String.valueOf(apiService.getDogDiary()))
                .replace("{{SAY_LOVE}}", String.valueOf(apiService.getSayLove()))
                .replace("{{ZAOAN}}", String.valueOf(apiService.getZaoAnInfo()))
                ;
    }

    /**
     * 恋爱天数计算逻辑
     *
     * @return
     */
    private String calculateLoveDays() {
        DateTime startDate = new DateTime(loveConfig.getLoveDay());
        return String.valueOf(DateUtil.between(startDate.toJdkDate(), new Date(), DateUnit.DAY, true));
    }


    /**
     * 生日倒计时计算逻辑
     *
     * @return
     */
    private String calculateMyBirthdayCountdown() {
        DateTime birthday = new DateTime(new DateTime().year() + "-" + loveConfig.getMyBirthday());
        if (DateUtil.between(birthday.toJdkDate(), new Date(), DateUnit.DAY) > 0) {
            birthday = birthday.offset(DateField.YEAR, 1);
        }
        return String.valueOf(DateUtil.between(birthday.toJdkDate(), new Date(), DateUnit.DAY, true));
    }

    /**
     * BB生日倒计时计算逻辑
     *
     * @return
     */
    private String calculateBbBirthdayCountdown() {
        DateTime birthday = new DateTime(new DateTime().year() + "-" + loveConfig.getHerBirthday());
        if (DateUtil.between(birthday.toJdkDate(), new Date(), DateUnit.DAY) > 0) {
            birthday = birthday.offset(DateField.YEAR, 1);
        }
        return String.valueOf(DateUtil.between(birthday.toJdkDate(), new Date(), DateUnit.DAY, true));
    }

}

